/*
 * Copyright 2009 Original Author(s)
 * 
 * This file is part of Kommando
 * 
 * Kommando is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Kommando is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Kommando.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.kommando.util.osgi;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;

/**
 * @author Peter De Bruycker
 */
public class ServiceUtils {
	public static <T> T getService(final BundleContext context, Class<T> serviceType) {
		final ServiceTracker tracker = new ServiceTracker(context, serviceType
				.getName(), null);
		tracker.open();
		// TODO close the tracker

		Object proxy = Proxy.newProxyInstance(serviceType.getClassLoader(),
				new Class[] { serviceType }, new InvocationHandler() {
					@Override
					public Object invoke(Object proxy, Method method,
							Object[] args) throws Throwable {
						Object delegate = tracker.getService();
						if (delegate == null) {
							throw new RuntimeException("no delegate found!");
						}
						
						return method.invoke(delegate, args);
					}
				});

		return serviceType.cast(proxy);
	}
}
